<template>
	<view class="record-container">
		<!-- 句子导航 -->
		<view class="sentence-nav">
			<button class="nav-btn" :disabled="currentOrder <= 1" @click="goToPrevious">
				<text class="nav-icon">‹</text>
				<text class="nav-text">上一个</text>
			</button>
			<view class="nav-info">
				<text class="nav-current">{{ currentOrder }}/{{ totalSentences }}</text>
			</view>
			<button class="nav-btn" :disabled="currentOrder >= totalSentences" @click="goToNext">
				<text class="nav-text">下一个</text>
				<text class="nav-icon">›</text>
			</button>
		</view>

		<view class="sentence-card">
			<view class="sentence-content">
				{{ sentenceContent }}
			</view>
		</view>
		
		<view class="record-box">
			<view class="waveform">
				<view class="wave-line" v-for="(item, index) in waveformData" :key="index" :style="{height: item + 'rpx'}"></view>
			</view>
			
			<view class="timer">
				<text>{{ formatTime(recordTime) }}</text>
			</view>
			
			<view class="controls">
				<view class="control-btn" @click="handleDelete" v-if="hasRecording">
					<text class="control-icon">🗑️</text>
					<text class="control-text">删除</text>
				</view>
				
				<view class="record-btn" :class="{ 'recording': isRecording }" @click="toggleRecord">
					<text class="record-icon">{{ isRecording ? '■' : '●' }}</text>
				</view>
				
				<view class="control-btn" @click="handlePlay" v-if="hasRecording">
					<text class="control-icon">▶️</text>
					<text class="control-text">播放</text>
				</view>
			</view>
			
			<button class="submit-btn" :disabled="!hasRecording || isSubmitting" @click="handleSubmit">
				{{ isSubmitting ? '提交中...' : '提交录音' }}
			</button>
		</view>
		
	</view>
</template>

<script>
	import { recordingAPI, sentenceAPI } from '../../utils/api.js';

	export default {
		data() {
			return {
				sentenceId: 0,
				sentenceContent: '',
				currentOrder: 1,
				totalSentences: 0, // 改为0，避免显示错误的初始值
				isRecording: false,
				hasRecording: false,
				isSubmitting: false,
				recordTime: 0,
				timer: null,
				waveformData: Array(40).fill(5),
				recorderManager: null,
				audioContext: null,
				tempFilePath: '',
				assignedSentences: [] // 存储所有分配的句子
			}
		},
		onLoad(options) {
			console.log('录音页面加载');
			if (options.id && options.content) {
				this.sentenceId = parseInt(options.id);
				this.sentenceContent = decodeURIComponent(options.content);
				this.currentOrder = parseInt(options.order) || 1;
				// 如果URL中有总数参数，直接使用
				if (options.total) {
					this.totalSentences = parseInt(options.total);
				}
				console.log('句子ID:', this.sentenceId);
				console.log('句子内容:', this.sentenceContent);
				console.log('当前顺序:', this.currentOrder);
				console.log('总句子数:', this.totalSentences);
			}

			// 获取所有分配的句子用于导航
			this.getAssignedSentences();

			// 初始化录音管理器
			this.initRecorder();
		},
		onUnload() {
			// 页面卸载时清理资源
			if (this.timer) {
				clearInterval(this.timer);
			}
			
			if (this.audioContext) {
				this.audioContext.destroy();
				this.audioContext = null;
			}
			
			// 确保录音停止
			if (this.isRecording && this.recorderManager) {
				this.recorderManager.stop();
			}
		},
		methods: {
			// 获取分配的句子列表
			getAssignedSentences() {
				// 如果已经有数据，就不重复请求
				if (this.assignedSentences.length > 0) {
					return;
				}

				sentenceAPI.getAssignedSentences()
					.then(res => {
						if (res.code === 200) {
							this.assignedSentences = res.data.sentences || [];
							this.totalSentences = this.assignedSentences.length;
							console.log('获取分配句子成功:', this.assignedSentences);
						}
					})
					.catch(err => {
						console.error('获取分配句子失败:', err);
					});
			},

			// 上一个句子
			goToPrevious() {
				if (this.currentOrder <= 1) return;

				const prevSentence = this.assignedSentences.find(s => s.sequence_order === this.currentOrder - 1);
				if (prevSentence) {
					uni.redirectTo({
						url: `/pages/record/record?id=${prevSentence.id}&content=${encodeURIComponent(prevSentence.content)}&order=${prevSentence.sequence_order}&total=${this.totalSentences}`
					});
				}
			},

			// 下一个句子
			goToNext() {
				if (this.currentOrder >= this.totalSentences) return;

				const nextSentence = this.assignedSentences.find(s => s.sequence_order === this.currentOrder + 1);
				if (nextSentence) {
					uni.redirectTo({
						url: `/pages/record/record?id=${nextSentence.id}&content=${encodeURIComponent(nextSentence.content)}&order=${nextSentence.sequence_order}&total=${this.totalSentences}`
					});
				}
			},

			// 初始化录音管理器
			initRecorder() {
				console.log('初始化录音管理器');
				// 创建录音管理器
				this.recorderManager = uni.getRecorderManager();
				console.log('录音管理器创建成功:', this.recorderManager);
				
				// 监听录音开始事件
				this.recorderManager.onStart(() => {
					console.log('录音开始事件触发');
					this.isRecording = true;
				});
				
				// 监听录音结束事件
				this.recorderManager.onStop((res) => {
					console.log('录音结束事件触发:', res);
					this.isRecording = false;
					
					// 确保有录音文件路径
					if (res && res.tempFilePath) {
						this.tempFilePath = res.tempFilePath;
						this.hasRecording = true;
						console.log('录音文件路径:', this.tempFilePath);
						
						// 创建音频上下文用于播放
						if (this.audioContext) {
							this.audioContext.destroy();
						}
						
						this.audioContext = uni.createInnerAudioContext();
						this.audioContext.src = this.tempFilePath;
						console.log('音频上下文创建成功');
						
						// 监听音频播放结束
						this.audioContext.onEnded(() => {
							console.log('音频播放结束');
						});
						
						// 监听音频播放错误
						this.audioContext.onError((err) => {
							console.error('音频播放错误：', err);
							uni.showToast({
								title: '音频播放失败',
								icon: 'none'
							});
						});
					} else {
						console.error('未获取到录音文件路径');
						uni.showToast({
							title: '录音保存失败，请重试',
							icon: 'none'
						});
					}
				});
				
				// 监听录音错误
				this.recorderManager.onError((res) => {
					console.error('录音错误：', res);
					this.isRecording = false;
					clearInterval(this.timer);
					
					uni.showToast({
						title: '录音失败，请重试',
						icon: 'none'
					});
				});
				
				// 监听录音进行中
				this.recorderManager.onFrameRecorded((res) => {
					// 可以在这里处理录音帧数据
					this.updateWaveform();
				});
			},
			
			// 切换录音状态
			toggleRecord() {
				console.log('点击录音按钮');
				if (this.isRecording) {
					this.stopRecord();
				} else {
					// 直接开始录音，不检查权限（权限会由系统自动请求）
					this.startRecord();
				}
			},
			
			// 检查录音权限
			checkPermission(callback) {
				// 直接调用回调，让系统自动处理权限请求
				callback && callback();
			},
			
			// 开始录音
			startRecord() {
				console.log('开始录音');
				// 重置状态
				this.recordTime = 0;
				this.hasRecording = false;
				
				// 开始计时
				this.timer = setInterval(() => {
					this.recordTime++;
				}, 1000);
				
				// 开始录音
				this.recorderManager.start({
					format: 'wav',
					sampleRate: 16000,
					numberOfChannels: 1,
					encodeBitRate: 96000
				});
				
				uni.showToast({
					title: '开始录音',
					icon: 'none'
				});
			},
			
			// 停止录音
			stopRecord() {
				// 停止计时
				clearInterval(this.timer);
				
				// 停止录音
				this.recorderManager.stop();
				
				uni.showToast({
					title: '录音已停止',
					icon: 'none'
				});
			},
			
			// 播放录音
			handlePlay() {
				if (!this.audioContext || !this.tempFilePath) {
					uni.showToast({
						title: '没有可播放的录音',
						icon: 'none'
					});
					return;
				}
				
				try {
					// 重置音频并播放
					this.audioContext.stop();
					setTimeout(() => {
						this.audioContext.seek(0);
						this.audioContext.play();
						
						uni.showToast({
							title: '正在播放',
							icon: 'none'
						});
					}, 100);
				} catch (e) {
					console.error('播放录音失败:', e);
					
					// 尝试重新创建音频上下文
					try {
						if (this.audioContext) {
							this.audioContext.destroy();
						}
						
						this.audioContext = uni.createInnerAudioContext();
						this.audioContext.src = this.tempFilePath;
						this.audioContext.play();
						
						// 监听音频播放结束
						this.audioContext.onEnded(() => {
							console.log('音频播放结束');
						});
						
						// 监听音频播放错误
						this.audioContext.onError((err) => {
							console.error('音频播放错误：', err);
							uni.showToast({
								title: '音频播放失败',
								icon: 'none'
							});
						});
						
						uni.showToast({
							title: '正在播放',
							icon: 'none'
						});
					} catch (err) {
						uni.showToast({
							title: '播放失败，请重试',
							icon: 'none'
						});
					}
				}
			},
			
			// 删除录音
			handleDelete() {
				uni.showModal({
					title: '提示',
					content: '确定要删除当前录音吗？',
					success: (res) => {
						if (res.confirm) {
							// 清理音频资源
							if (this.audioContext) {
								this.audioContext.destroy();
								this.audioContext = null;
							}
							
							this.hasRecording = false;
							this.recordTime = 0;
							this.tempFilePath = '';
							this.waveformData = Array(40).fill(5);
							
							uni.showToast({
								title: '录音已删除',
								icon: 'none'
							});
						}
					}
				});
			},
			
			// 提交录音
			handleSubmit() {
				if (!this.hasRecording || !this.tempFilePath) {
					uni.showToast({
						title: '请先录音',
						icon: 'none'
					});
					return;
				}
				
				this.isSubmitting = true;
				
				// 上传录音
				recordingAPI.uploadRecording(this.sentenceId, this.tempFilePath)
					.then(res => {
						console.log('上传录音响应:', res);
						// 检查各种可能的成功响应格式
						if (
							(res.code === 200) ||
							(res.data && res.data.code === 200) ||
							res.message === '上传成功' ||
							(res.data && res.data.id)
						) {
							uni.showToast({
								title: '提交成功',
								icon: 'success',
								duration: 1500
							});

							// 检查是否有下一个句子
							setTimeout(() => {
								if (this.currentOrder < this.totalSentences) {
									// 有下一个句子，自动跳转
									const nextSentence = this.assignedSentences.find(s => s.sequence_order === this.currentOrder + 1);
									if (nextSentence) {
										uni.redirectTo({
											url: `/pages/record/record?id=${nextSentence.id}&content=${encodeURIComponent(nextSentence.content)}&order=${nextSentence.sequence_order}&total=${this.totalSentences}`
										});
									} else {
										this.goToNext();
									}
								} else {
									// 所有句子录制完成
									uni.showModal({
										title: '恭喜',
										content: '所有录音任务已完成！',
										showCancel: false,
										success: () => {
											uni.navigateBack();
										}
									});
								}
							}, 1500);
						} else {
							// 如果不符合任何成功条件，则抛出错误
							throw new Error((res.message || res.data?.message || '上传失败'));
						}
					})
					.catch(err => {
						// 只有在明确失败时才显示错误提示
						if (err && err.message !== '上传成功') {
							console.error('上传录音失败', err);
							uni.showToast({
								title: '上传失败，请重试',
								icon: 'none'
							});
						}
					})
					.finally(() => {
						this.isSubmitting = false;
					});
			},
			
			// 格式化时间
			formatTime(seconds) {
				const minutes = Math.floor(seconds / 60);
				const remainingSeconds = seconds % 60;
				return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
			},
			
			// 更新波形图
			updateWaveform() {
				// 生成波形数据
				this.waveformData = this.waveformData.map(() => {
					return Math.floor(Math.random() * 40) + 5;
				});
			}
		}
	}
</script>

<style lang="scss">
	.record-container {
		position: relative;
		min-height: 100vh;
		background-color: #E0E6E9; // 莫兰迪淡灰蓝背景
		padding: 30rpx;
	}
	
	// 句子导航样式
	.sentence-nav {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 30rpx;
		padding: 20rpx;
		background-color: rgba(255, 255, 255, 0.95);
		border-radius: 15rpx;
		border: 2rpx solid #D1C8BC;

		.nav-btn {
			display: flex;
			align-items: center;
			padding: 15rpx 25rpx;
			background-color: #8A9EA8;
			color: white;
			border: none;
			border-radius: 25rpx;
			font-size: 26rpx;

			&[disabled] {
				background-color: #ccc;
				opacity: 0.6;
			}

			.nav-icon {
				font-size: 32rpx;
				font-weight: bold;
			}

			.nav-text {
				margin: 0 8rpx;
			}
		}

		.nav-info {
			.nav-current {
				font-size: 28rpx;
				color: #8A9EA8;
				font-weight: bold;
			}
		}
	}

	.sentence-card {
		background-color: rgba(255, 255, 255, 0.95);
		border-radius: 20rpx;
		padding: 50rpx 40rpx;
		margin-bottom: 40rpx;
		border: 3rpx solid #D1C8BC;
		min-height: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.sentence-content {
			font-size: 48rpx;
			color: #333;
			line-height: 1.8;
			text-align: center;
			font-weight: 500;
			letter-spacing: 2rpx;
			word-break: break-all;
		}
	}
	
	.record-box {
		background-color: rgba(255, 255, 255, 0.95);
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 40rpx;
		border: 3rpx solid #D1C8BC; // 莫兰迪淡棕色边框
		
		.waveform {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 0;
			
			.wave-line {
				width: 6rpx;
				background-color: #8A9EA8; // 莫兰迪灰蓝色
				border-radius: 3rpx;
			}
		}
		
		.timer {
			text-align: center;
			margin: 20rpx 0;
			font-size: 40rpx;
			color: #8A9EA8; // 莫兰迪灰蓝色
			font-weight: bold;
		}
		
		.controls {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 40rpx 0;
			
			.control-btn {
				display: flex;
				flex-direction: column;
				align-items: center;
				margin: 0 60rpx;
				
				.control-icon {
					font-size: 48rpx;
					margin-bottom: 10rpx;
				}
				
				.control-text {
					font-size: 24rpx;
					color: #666;
				}
			}
			
			.record-btn {
				width: 120rpx;
				height: 120rpx;
				border-radius: 60rpx;
				background-color: #E0E6E9; // 莫兰迪淡灰蓝背景
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0 40rpx;
				border: 3rpx solid #D1C8BC; // 莫兰迪淡棕色边框
				
				&.recording {
					background-color: #8A9EA8; // 莫兰迪灰蓝色
					animation: pulse 1.5s infinite;
				}
				
				.record-icon {
					font-size: 48rpx;
					color: #fff;
				}
			}
		}
		
		.submit-btn {
			height: 90rpx;
			line-height: 90rpx;
			background: linear-gradient(135deg, #8A9EA8, #B6C5CD); // 莫兰迪灰蓝渐变
			color: #fff;
			font-size: 32rpx;
			border-radius: 45rpx;
			margin-top: 30rpx;
			border: 2rpx solid #D1C8BC; // 莫兰迪淡棕色边框
			
			&[disabled] {
				opacity: 0.6;
				background: #999;
			}
		}
	}
	

	
	@keyframes pulse {
		0% {
			transform: scale(1);
		}
		50% {
			transform: scale(1.1);
		}
		100% {
			transform: scale(1);
		}
	}
</style> 